from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.db import models
from itsdangerous import TimedJSONWebSignatureSerializer, BadData

# Create your models here.
from areas.models import Areas


class User(AbstractUser):
    """
    用户信息
    """
    mobile = models.CharField(max_length=11, unique=True, null=True, blank=True, verbose_name=u"手机号")
    nickname = models.CharField(max_length=11, null=True, blank=True, verbose_name=u"昵称")
    email_active = models.BooleanField(default=False, verbose_name=u"邮箱验证状态")

    class Meta:
        db_table = "tb_users"
        verbose_name = u"用户"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username

    def generate_send_sms_code_token(self):
        serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, 600)
        data = {
            'mobile': self.mobile
        }
        token = serializer.dumps(data)
        return token.decode()

    @staticmethod
    def check_send_sms_code_token(token):
        """
        检验access_token
        :param token:access_token
        :return:
        """
        serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, 300)
        try:
            data = serializer.loads(token)
        except BadData:
            return False
        else:
            mobile = data.get("mobile")
            return mobile

    def generate_email_verify_token(self):
        """
        生成邮箱验证连接
        :return: 邮箱验证连接
        """
        serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, 60 * 60 * 24)
        data = {
            "email": self.email,
            "user_id": self.id
        }
        token = serializer.dumps(data)
        return token.decode()

